// ============================================================================
// IPC 管理器
// ============================================================================

import { ipcMain, BrowserWindow } from 'electron'
import { Container } from './container'
import { IPC_EVENTS } from '../../shared/constants'
import { IPCResponse } from '../../shared/types'
import { WeiboLoginManager } from '../login/weibo-login'
import { TaskManager } from '../tasks/task-manager'
import { ConfigManager } from '../config/config-manager'
import { TaskScheduler } from './scheduler'
import { WeiboWorkflowService } from '../services/weibo-workflow-service'
import { LoggerService } from './logger-service'
import { ErrorHandler } from './error-handler'
import { logger } from '@roasmax/logger'
import { useEntityManager } from '../storage/data-source'
import { Account, WeiboData, TaskLog } from '../storage/entities'
import { Like } from 'typeorm'
import { keywordWindowController } from '../controllers/keyword-window-controller'

/**
 * IPC处理器接口
 */
interface IPCHandler {
  handle(event: Electron.IpcMainInvokeEvent, ...args: any[]): Promise<IPCResponse>
}

/**
 * IPC管理器
 * 负责设置和管理所有IPC通信
 */
export class IPCManager {
  private container: Container
  private logger: LoggerService
  private errorHandler: ErrorHandler
  private handlers = new Map<string, IPCHandler>()

  constructor(container: Container) {
    this.container = container
    this.logger = container.get<LoggerService>('logger')
    this.errorHandler = container.get<ErrorHandler>('errorHandler')
  }

  /**
   * 初始化IPC管理器
   */
  async initialize(): Promise<void> {
    try {
      this.logger.info('Initializing IPC manager')
      
      // 注册IPC处理器
      this.registerHandlers()
      
      // 设置IPC事件监听
      this.setupIPCListeners()
      
      this.logger.info('IPC manager initialized successfully')
      
    } catch (error) {
      this.logger.error('Failed to initialize IPC manager:', error)
      throw error
    }
  }

  /**
   * 注册IPC处理器
   */
  private registerHandlers(): void {
    // 获取服务实例
    const browserManagerFactory = this.container.get<() => any>('browserManagerFactory')
    const loginManager = new WeiboLoginManager(browserManagerFactory)
    const taskManager = new TaskManager()
    const configManager = this.container.get<ConfigManager>('configManager')
    
    // 设置主窗口引用
    const mainWindow = this.container.get<BrowserWindow>('mainWindow')
    if (mainWindow) {
      taskManager.setMainWindow(mainWindow)
    }

    // 注册登录相关处理器
    this.registerLoginHandlers(loginManager)
    
    // 注册任务相关处理器
    this.registerTaskHandlers(taskManager)
    
    // 注册配置相关处理器
    this.registerConfigHandlers(configManager)
    
    // 注册数据相关处理器
    this.registerDataHandlers(taskManager)

    // 注册定时任务相关处理器
    try {
      const scheduler = this.container.get<TaskScheduler>('scheduler')
      this.registerSchedulerHandlers(scheduler)
    } catch (error) {
      logger.warn('调度器服务未找到，跳过定时任务处理器注册', error)
    }

    // 注册工作流相关处理器
    try {
      const workflowService = this.container.get<WeiboWorkflowService>('workflowService')
      logger.info('工作流服务获取成功，注册处理器')
      this.registerWorkflowHandlers(workflowService)
    } catch (error) {
      logger.warn('工作流服务未找到，跳过工作流处理器注册', error)
    }

    // 注册关键字窗口相关处理器
    this.registerKeywordWindowHandlers()
    
    // 注册系统相关处理器
    this.registerSystemHandlers()
  }

  /**
   * 注册登录相关处理器
   */
  private registerLoginHandlers(loginManager: WeiboLoginManager): void {
    this.handlers.set(IPC_EVENTS.LOGIN_START, {
      handle: async () => {
        const loginData = await loginManager.startLogin()
        return this.createSuccessResponse(loginData)
      }
    })

    this.handlers.set(IPC_EVENTS.LOGIN_VALIDATE, {
      handle: async (_, accountId: string) => {
        const result = await loginManager.validateSession(accountId)
        return this.createSuccessResponse(result)
      }
    })

    this.handlers.set(IPC_EVENTS.LOGIN_GET_ACCOUNTS, {
      handle: async () => {
        const accounts = await loginManager.getStoredAccounts()
        return this.createSuccessResponse(accounts)
      }
    })

    this.handlers.set(IPC_EVENTS.LOGIN_DELETE_ACCOUNT, {
      handle: async (_, accountId: string) => {
        try {
          await useEntityManager(async m=>{
            const a = m.getRepository(Account)
            return a.delete(accountId)
          })
          return this.createSuccessResponse(true)
        } catch (error) {
          this.logger.error('删除账号失败', error)
          throw error
        }
      }
    })

    this.handlers.set(IPC_EVENTS.LOGIN_DELETE_INVALID_ACCOUNTS, {
      handle: async () => {
        try {
          const deletedCount = await useEntityManager(async m => {
            const accountRepo = m.getRepository(Account)
            const result = await accountRepo.delete({ isValid: false })
            return result.affected || 0
          })
          return this.createSuccessResponse(deletedCount)
        } catch (error) {
          this.logger.error('删除无效账号失败', error)
          throw error
        }
      }
    })
  }

  /**
   * 注册任务相关处理器
   */
  private registerTaskHandlers(taskManager: TaskManager): void {
    this.handlers.set(IPC_EVENTS.TASK_CREATE, {
      handle: async (_, taskData) => {
        const task = await taskManager.createTask(taskData)
        return this.createSuccessResponse(task)
      }
    })

    this.handlers.set(IPC_EVENTS.TASK_START, {
      handle: async (_, taskId: string) => {
        // await taskManager.startTask(taskId)
        return this.createSuccessResponse(undefined)
      }
    })

    this.handlers.set(IPC_EVENTS.TASK_STOP, {
      handle: async (_, taskId: string) => {
        await taskManager.stopTask(taskId)
        return this.createSuccessResponse(undefined)
      }
    })

    this.handlers.set(IPC_EVENTS.TASK_GET_ALL, {
      handle: async () => {
        const tasks = await taskManager.getAllTasks()
        return this.createSuccessResponse(tasks)
      }
    })

    this.handlers.set(IPC_EVENTS.TASK_GET_BY_ID, {
      handle: async (_, taskId: string) => {
        const task = await taskManager.getTaskById(taskId)
        return this.createSuccessResponse(task)
      }
    })
  }

  /**
   * 注册配置相关处理器
   */
  private registerConfigHandlers(configManager: ConfigManager): void {
    this.handlers.set(IPC_EVENTS.CONFIG_GET, {
      handle: async () => {
        const config = await configManager.getConfig()
        return this.createSuccessResponse(config)
      }
    })

    this.handlers.set(IPC_EVENTS.CONFIG_UPDATE, {
      handle: async (_, configUpdate) => {
        await configManager.updateConfig(configUpdate)
        return this.createSuccessResponse(undefined)
      }
    })
  }

  /**
   * 注册数据相关处理器
   */
  private registerDataHandlers(taskManager: TaskManager): void {
    this.handlers.set(IPC_EVENTS.DATA_EXPORT, {
      handle: async (_, taskId: string, format: string) => {
        const filePath = await taskManager.exportTaskData(taskId, format as any)
        return this.createSuccessResponse(filePath)
      }
    })

    this.handlers.set(IPC_EVENTS.DATA_GET_STATS, {
      handle: async () => {
        const stats = await taskManager.getStats()
        return this.createSuccessResponse(stats)
      }
    })

    // 微博数据统计处理器
    this.handlers.set(IPC_EVENTS.DATA_GET_WEIBO_STATS, {
      handle: async () => {
        const stats = await taskManager.getWeiboDataStats()
        return this.createSuccessResponse(stats)
      }
    })

    // 微博数据列表处理器
    this.handlers.set(IPC_EVENTS.DATA_GET_WEIBO_LIST, {
      handle: async (_, params: {
        page: number
        pageSize: number
        keyword?: string
        filterType?: 'all' | 'original' | 'repost'
        sortBy?: 'createdAt' | 'publishedAt' | 'interactions'
        sortOrder?: 'asc' | 'desc'
      }) => {
        const result = await taskManager.getWeiboDataList(params)
        return this.createSuccessResponse(result)
      }
    })

    // 用户数据统计处理器
    this.handlers.set(IPC_EVENTS.DATA_GET_USER_STATS, {
      handle: async () => {
        const stats = await taskManager.getUserDataStats()
        return this.createSuccessResponse(stats)
      }
    })

    // 用户数据列表处理器
    this.handlers.set(IPC_EVENTS.DATA_GET_USER_LIST, {
      handle: async (_, params: {
        page: number
        pageSize: number
        keyword?: string
        filterType?: 'all' | 'vip' | 'verified' | 'normal'
        sortBy?: 'createdAt' | 'followersCount' | 'statusesCount'
        sortOrder?: 'asc' | 'desc'
      }) => {
        const result = await taskManager.getUserDataList(params)
        return this.createSuccessResponse(result)
      }
    })

    // 调试用户数据处理器
    this.handlers.set(IPC_EVENTS.DEBUG_USER_DATA, {
      handle: async () => {
        await taskManager.debugUserData()
        return this.createSuccessResponse({ message: '调试信息已输出到日志' })
      }
    })

    // 批量更新用户完整信息处理器
    this.handlers.set(IPC_EVENTS.UPDATE_USERS_COMPLETE_INFO, {
      handle: async (_, params: { limit?: number } = {}) => {
        // 获取当前登录账户的cookies
        const accounts = await useEntityManager(async m => {
          const accountRepo = m.getRepository(Account)
          return await accountRepo.find()
        })

        if (accounts.length === 0) {
          throw new Error('没有可用的登录账户，请先登录微博账户')
        }

        const account = accounts[0]! // 使用第一个账户
        const cookies = JSON.parse(account.cookies)

        await taskManager.updateUsersCompleteInfo(cookies, params.limit || 10)
        return this.createSuccessResponse({ message: '批量更新完成' })
      }
    })

    this.handlers.set(IPC_EVENTS.DATA_GET_WEIBO_DATA, {
      handle: async (_, taskId: string, page: number = 1, pageSize: number = 100) => {
        const offset = (page - 1) * pageSize

        const [data, total] = await useEntityManager(async m => {
          const weiboRepo = m.getRepository(WeiboData)

          const [items, count] = await Promise.all([
            weiboRepo.find({
              where: { taskId },
              order: { createdAt: 'DESC' },
              take: pageSize,
              skip: offset
            }),
            weiboRepo.count({ where: { taskId } })
          ])

          return [items.map(item => item.toWeiboDataFormat()), count]
        })

        const result = {
          items: data,
          total,
          page,
          pageSize,
          hasMore: offset + pageSize < total
        }

        return this.createSuccessResponse(result)
      }
    })

    this.handlers.set(IPC_EVENTS.DATA_SEARCH_WEIBO, {
      handle: async (_, query: string, _filters?: any) => {
        const data = await useEntityManager(async m => {
          const weiboRepo = m.getRepository(WeiboData)

          const items = await weiboRepo.find({
            where: [
              { text: Like(`%${query}%`) },
              { userNickname: Like(`%${query}%`) }
            ],
            order: { createdAt: 'DESC' },
            take: 100
          })

          return items.map(item => item.toWeiboDataFormat())
        })

        const result = {
          items: data,
          total: data.length,
          page: 1,
          pageSize: 100,
          hasMore: false
        }
        return this.createSuccessResponse(result)
      }
    })
  }

  /**
   * 注册系统相关处理器
   */
  private registerSystemHandlers(): void {
    this.handlers.set('system:get-info', {
      handle: async () => {
        const info = {
          version: process.env.npm_package_version || '1.0.0',
          platform: process.platform,
          arch: process.arch,
          nodeVersion: process.version
        }
        return this.createSuccessResponse(info)
      }
    })

    // 任务日志相关处理器
    this.handlers.set(IPC_EVENTS.TASK_GET_LOGS, {
      handle: async (_, page: number = 1, pageSize: number = 100, level?: string) => {
        const offset = (page - 1) * pageSize

        const [logs, total] = await useEntityManager(async m => {
          const logRepo = m.getRepository(TaskLog)

          const whereCondition: any = {}
          if (level) {
            whereCondition.level = level
          }

          const [items, count] = await Promise.all([
            logRepo.find({
              where: whereCondition,
              order: { createdAt: 'DESC' },
              take: pageSize,
              skip: offset,
              relations: ['task']
            }),
            logRepo.count({ where: whereCondition })
          ])

          return [items.map(item => item.toTaskLogEntry()), count]
        })

        const result = {
          items: logs,
          total,
          page,
          pageSize,
          hasMore: offset + pageSize < total
        }

        return this.createSuccessResponse(result)
      }
    })

    this.handlers.set(IPC_EVENTS.TASK_GET_LOGS_BY_ID, {
      handle: async (_, taskId: string, page: number = 1, pageSize: number = 100) => {
        const offset = (page - 1) * pageSize

        const [logs, total] = await useEntityManager(async m => {
          const logRepo = m.getRepository(TaskLog)

          const [items, count] = await Promise.all([
            logRepo.find({
              where: { taskId },
              order: { createdAt: 'DESC' },
              take: pageSize,
              skip: offset
            }),
            logRepo.count({ where: { taskId } })
          ])

          return [items.map(item => item.toTaskLogEntry()), count]
        })

        const result = {
          items: logs,
          total,
          page,
          pageSize,
          hasMore: offset + pageSize < total
        }

        return this.createSuccessResponse(result)
      }
    })
  }

  /**
   * 设置IPC事件监听
   */
  private setupIPCListeners(): void {
    for (const [eventName, handler] of this.handlers) {
      ipcMain.handle(eventName, async (event, ...args) => {
        try {
          const response = await handler.handle(event, ...args)
          return response
        } catch (error) {
          this.logger.error(`IPC error: ${eventName}`, error)
          this.errorHandler.handleError(error as Error, `IPC:${eventName}`)
          return this.createErrorResponse(error as Error)
        }
      })
    }
  }

  /**
   * 创建成功响应
   */
  private createSuccessResponse<T>(data: T): IPCResponse<T> {
    return {
      success: true,
      data
    }
  }

  /**
   * 创建错误响应
   */
  private createErrorResponse(error: Error): IPCResponse {
    return {
      success: false,
      error: {
        code: 'IPC_ERROR',
        message: error.message,
        details: error.stack
      }
    }
  }

  /**
   * 注册定时任务相关处理器
   */
  private registerSchedulerHandlers(scheduler: TaskScheduler): void {
    // 获取工作流服务
    const workflowService = this.container.get<WeiboWorkflowService>('workflowService')
    logger.info('在 registerSchedulerHandlers 中获取工作流服务成功')

    this.handlers.set(IPC_EVENTS.SCHEDULER_CREATE_TASK, {
      handle: async (_, keywords: string[], accountId: string, options: any) => {
        const taskId = await workflowService.createScheduledWeiboTask(keywords, accountId, options)
        return this.createSuccessResponse(taskId)
      }
    })

    this.handlers.set(IPC_EVENTS.SCHEDULER_UPDATE_TASK, {
      handle: async (_, taskId: string, updates: any) => {
        await workflowService.updateScheduledTask(taskId, updates)
        return this.createSuccessResponse(null)
      }
    })

    this.handlers.set(IPC_EVENTS.SCHEDULER_DELETE_TASK, {
      handle: async (_, taskId: string) => {
        await workflowService.deleteScheduledTask(taskId)
        return this.createSuccessResponse(null)
      }
    })

    this.handlers.set(IPC_EVENTS.SCHEDULER_GET_STATUS, {
      handle: async () => {
        const status = scheduler.getStatus()
        return this.createSuccessResponse(status)
      }
    })

    this.handlers.set(IPC_EVENTS.SCHEDULER_GET_ALL_TASKS, {
      handle: async () => {
        const tasks = await workflowService.getAllScheduledTasks()
        return this.createSuccessResponse(tasks)
      }
    })

    this.handlers.set(IPC_EVENTS.SCHEDULER_EXECUTE_NOW, {
      handle: async (_, taskId: string) => {
        await workflowService.executeScheduledTaskNow(taskId)
        return this.createSuccessResponse(null)
      }
    })

    this.handlers.set(IPC_EVENTS.SCHEDULER_START, {
      handle: async () => {
        await scheduler.start()
        return this.createSuccessResponse(null)
      }
    })

    this.handlers.set(IPC_EVENTS.SCHEDULER_STOP, {
      handle: async () => {
        await scheduler.stop()
        return this.createSuccessResponse(null)
      }
    })
  }

  /**
   * 注册工作流相关处理器
   */
  private registerWorkflowHandlers(workflowService: WeiboWorkflowService): void {
    this.handlers.set(IPC_EVENTS.WORKFLOW_EXECUTE, {
      handle: async (_, keywords: string[], accountId: string, options: any) => {
        const stats = await workflowService.executeWeiboWorkflow(keywords, accountId, options)
        return this.createSuccessResponse(stats)
      }
    })

    this.handlers.set(IPC_EVENTS.WORKFLOW_GET_STATS, {
      handle: async () => {
        const stats = workflowService.getCurrentStats()
        return this.createSuccessResponse(stats)
      }
    })

    this.handlers.set(IPC_EVENTS.WORKFLOW_UPDATE_CONFIG, {
      handle: async (_, config: any) => {
        workflowService.updateConfig(config)
        return this.createSuccessResponse(null)
      }
    })
  }

  /**
   * 注册关键字窗口相关处理器
   */
  private registerKeywordWindowHandlers(): void {
    // 获取所有关键字窗口
    this.handlers.set('keyword-window:get-all', {
      handle: async () => {
        try {
          return await keywordWindowController.getAllWindowsIPC()
        } catch (error) {
          logger.error('IPC: 获取关键字窗口列表失败', error)
          return this.createErrorResponse(error as Error)
        }
      }
    })

    // 获取关键字窗口详情
    this.handlers.set('keyword-window:get-details', {
      handle: async (_, keyword: string) => {
        try {
          return await keywordWindowController.getKeywordWindowIPC(keyword)
        } catch (error) {
          logger.error('IPC: 获取关键字窗口详情失败', error)
          return this.createErrorResponse(error as Error)
        }
      }
    })

    // 更新关键字窗口设置
    this.handlers.set('keyword-window:update', {
      handle: async (_, keyword: string, updates: any) => {
        try {
          return await keywordWindowController.updateKeywordWindowIPC(keyword, updates)
        } catch (error) {
          logger.error('IPC: 更新关键字窗口失败', error)
          return this.createErrorResponse(error as Error)
        }
      }
    })

    // 重置关键字窗口
    this.handlers.set('keyword-window:reset', {
      handle: async (_, keyword: string) => {
        try {
          return await keywordWindowController.resetKeywordWindowIPC(keyword)
        } catch (error) {
          logger.error('IPC: 重置关键字窗口失败', error)
          return this.createErrorResponse(error as Error)
        }
      }
    })

    // 删除关键字窗口
    this.handlers.set('keyword-window:delete', {
      handle: async (_, keyword: string) => {
        try {
          return await keywordWindowController.deleteKeywordWindowIPC(keyword)
        } catch (error) {
          logger.error('IPC: 删除关键字窗口失败', error)
          return this.createErrorResponse(error as Error)
        }
      }
    })

    // 获取关键字时间范围
    this.handlers.set('keyword-window:get-time-ranges', {
      handle: async (_, keyword: string) => {
        try {
          return await keywordWindowController.getKeywordTimeRangesIPC(keyword)
        } catch (error) {
          logger.error('IPC: 获取关键字时间范围失败', error)
          return this.createErrorResponse(error as Error)
        }
      }
    })

    // 获取需要历史爬取的关键字列表
    this.handlers.set('keyword-window:get-history-crawl-needed', {
      handle: async (_, interval?: number) => {
        try {
          logger.debug('IPC: 开始处理历史爬取请求', { interval })
          
          const response = await keywordWindowController.getKeywordsNeedingHistoryCrawlIPC(interval)
          
          logger.debug('IPC: 直接IPC方法返回结果', {
            responseSuccess: response.success,
            responseData: response.data,
            responseError: response.error,
            dataType: typeof response.data,
            dataKeys: response.data ? Object.keys(response.data) : null
          })
          
          return response
        } catch (error) {
          logger.error('IPC: 获取历史爬取关键字失败', error)
          return this.createErrorResponse(error as Error)
        }
      }
    })
    
    logger.info('关键字窗口IPC处理器注册完成')
  }

  /**
   * 清理IPC监听器
   */
  cleanup(): void {
    for (const eventName of this.handlers.keys()) {
      ipcMain.removeAllListeners(eventName)
    }
    this.handlers.clear()
  }
}
